package persistencia.HSQL;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import persistencia.DAOS.InicializacionDAO;

public class HSQLInicializacionDAO implements InicializacionDAO{
	private static Connection connection;
	
	public void createTablas() {
		conectar();		
		try {
			Statement stm = connection.createStatement();
			
			File file = new File("src/datos/creates.sql");
			FileReader in = new FileReader(file);
			BufferedReader bf = new BufferedReader(in);
			String s;
			
			while((s = bf.readLine()) != null)
				if(s.length() > 1)
					stm.executeQuery(s);
			
			desconectar();
			bf.close();
			stm.close();
		}
		
		catch (SQLException e) {
			e.printStackTrace();
		}
		
		catch (FileNotFoundException nf){
			nf.printStackTrace();
		}
		
		catch (IOException io){
			io.printStackTrace();
		}
	}

	public void cargarTablas() {
		conectar();		
		try {
			Statement stm = connection.createStatement();
			
			File file = new File("src/datos/inserts.txt");
			FileReader in = new FileReader(file);
			BufferedReader bf = new BufferedReader(in);
			String s;
			
			while((s = bf.readLine()) != null)
				if(s.length() > 1){
					System.out.println(s);
					stm.executeQuery(s);
				}
					
			desconectar();
			bf.close();
			stm.close();
		}
		
		catch (SQLException e) {
			e.printStackTrace();
		}
		
		catch (FileNotFoundException nf){
			nf.printStackTrace();
		}
		
		catch (IOException io){
			io.printStackTrace();
		}
	}
	
	public static void conectar(){
		connection = null;
		try {
			Class.forName("org.hsqldb.jdbcDriver");
			connection = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/", "sa", ""); 	
		}
		
		catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	public static void desconectar(){
		try {
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
}